import { useState, useEffect } from 'react';
import { Checkbox, Toast, TabBar } from 'antd-mobile';
import './shopping.css';
import { shopping } from '../../api/shopping'
import { home,addCart } from '../../api/home'
import { useNavigate, useLocation } from 'react-router-dom'


// 添加购物车图标
import add from '../../assets/add.png'
// 添加成功图标
import ok from '../../assets/ok.png'

// 猜你喜欢左边爱心
import loveLeft from "../../assets/leftlove.png"

// 猜你喜欢右边爱心
import loveRight from "../../assets/lovelike.png"

import {
  AppOutline,
  MessageOutline,
  MessageFill,
  UnorderedListOutline,
  UserOutline,
} from 'antd-mobile-icons'


let url='http://jingxun.kuxia.top'

const ShoppingCart = () => {
  const navigate = useNavigate()
  const location = useLocation()
  
 // 购物车商品数据
  const [cartItems, setCartItems] = useState([]);
  // 添加购物车商品状态
  // Deleted: const [cartItems, setCartItems] = useState({})
  
  // 添加加载状态
  const [loading, setLoading] = useState(false);
  
  // 猜你喜欢商品数据
  const [recommendItems, setRecommendItems] = useState([]);
  // 页面加载时获取购物车数据
  useEffect(() => {
    fetchCartData();
    fetchRecommendData();
  }, []);

  // 获取购物车数据
  const fetchCartData = async () => {
    try {
      setLoading(true);
      // 从本地存储获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userId = userInfo.id;
      
      if (!userId) {
        Toast.show({
          content: '未找到用户信息，请重新登录',
          position: 'top'
        });
        setCartItems([]);
        return;
      }
      
      // 调用购物车接口
      const response = await shopping({ id: userId });
      console.log('购物车数据', response);
      
      // 处理接口返回的数据
      if (response && response.data) {
        // 根据接口数据结构转换为组件所需的数据结构
        const items = response.data.map(item => {
          // 从commodity数组中获取商品信息
          const commodity = item.commodity && item.commodity.length > 0 ? item.commodity[0] : {};
          
          return {
            id: item.id, // 使用购物车项的id
            name: commodity.title || '',
            price: parseFloat(commodity.price) || 0,
            image: commodity.image || 'https://via.placeholder.com/100',
            quantity: item.num || 1, // 使用购物车中的数量
            checked: false, // 默认未选中
            commodity_id: item.commodity_id // 保存商品id
          };
        });
        setCartItems(items);
      } else {
        setCartItems([]);
      }
    } catch (error) {
      Toast.show({
        content: '获取购物车数据失败',
        position: 'top'
      });
      console.error('获取购物车数据失败:', error);
      setCartItems([]);
    } finally {
      setLoading(false);
    }
  };

  // 添加商品到购物车
    const handleAddToCart = async (commodityId) => {
      try {
        // 从本地存储获取用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const userId = userInfo.id;
        
        if (!userId) {
          Toast.show({
            content: '请先登录',
            position: 'top'
          });
          return;
        }
        
        // 调用添加购物车接口
        const response = await addCart({
          user_id: userId,
          commodity_id: commodityId,
          num: "1"
        });
        
        if (response.code === 1) {
          // 更新购物车状态
          // Deleted: setCartItems(prev => ({
          // Deleted:   ...prev,
          // Deleted:   [commodityId]: true
          // Deleted: }));
          
          // 重新获取购物车数据
          await fetchCartData();
          
          Toast.show({
            content: '添加成功',
            position: 'top'
          });
        } else {
          Toast.show({
            content: '添加失败',
            position: 'top'
          });
        }
      } catch (error) {
        Toast.show({
          content: '添加失败',
          position: 'top'
        });
        console.error('添加购物车失败:', error);
      }
    };
  
  // 获取推荐商品数据
  const fetchRecommendData = async () => {
    try {
      const response = await home();
      console.log('推荐商品数据', response);
      
      // 处理接口返回的数据
      if (response && response.data && response.data.commodity) {
        setRecommendItems(response.data.commodity);
      }
    } catch (error) {
      Toast.show({
        content: '获取推荐商品数据失败',
        position: 'top'
      });
      console.error('获取推荐商品数据失败:', error);
    }
  };

  const tabs = [
    {
      key: '/home',
      title: '首页',
      icon: <AppOutline />,
    },
    {
      key: '/todo',
      title: '分类',
      icon: <UnorderedListOutline />,
    },
    {
      key: '/shopping',
      title: '购物车',
      icon: <MessageOutline />,
    },
    {
      key: '/mine',
      title: '我的',
      icon: <UserOutline />,
    },
  ]

  const [activeKey, setActiveKey] = useState(location.pathname)

  useEffect(() => {
    setActiveKey(location.pathname)
  }, [location.pathname])

  const setRouteActive = (key) => {
    setActiveKey(key)
    navigate(key)
  }

  // 全选状态
  const isAllChecked = cartItems.length > 0 && cartItems.every(item => item.checked);

  // 计算选中商品总数量
  const selectedCount = cartItems.filter(item => item.checked).reduce((total, item) => total + item.quantity, 0);

  // 计算选中商品总价
  const totalPrice = cartItems.filter(item => item.checked).reduce((total, item) => total + (item.price * item.quantity), 0);

  // 处理全选/取消全选
  const handleCheckAll = (checked) => {
    setCartItems(cartItems.map(item => ({
      ...item,
      checked
    })));
  };

  // 处理单个商品选中状态
  const handleItemCheck = (id, checked) => {
    setCartItems(cartItems.map(item => 
      item.id === id ? { ...item, checked } : item
    ));
  };

  // 增加商品数量
  const increaseQuantity = (id) => {
    setCartItems(cartItems.map(item => 
      item.id === id ? { ...item, quantity: item.quantity + 1 } : item
    ));
  };

  // 减少商品数量
  const decreaseQuantity = (id) => {
    setCartItems(cartItems.map(item => 
      item.id === id && item.quantity > 1 ? { ...item, quantity: item.quantity - 1 } : item
    ));
  };

  // 删除商品
  const deleteItem = (id) => {
    setCartItems(cartItems.filter(item => item.id !== id));
    Toast.show({
      content: '商品已删除',
      position: 'top'
    });
  };
  
  // 将商品数据分为两列（瀑布流）
  const renderWaterfall = () => {
    const leftColumn = [];
    const rightColumn = [];
    
    recommendItems.forEach((item, index) => {
      if (index % 2 === 0) {
        leftColumn.push(item);
      } else {
        rightColumn.push(item);
      }
    });
    
    return { leftColumn, rightColumn };
  };
  
  const { leftColumn, rightColumn } = renderWaterfall();

  return (
    <div className="shopping">
      {/* 购物车标题 */}
      <div className="shopping-title">
        购物车
      </div>

      {/* 购物车列表 */}
      {loading ? (
        <div className="loading">加载中...</div>
      ) : cartItems.length > 0 ? (
        <>
          <div className="cart-items">
            {cartItems.map(item => (
              <div className="cart-item" key={item.id}>
                {/* 商品选中复选框 */}
                <div className="item-checkbox">
                  <Checkbox 
                    checked={item.checked} 
                    onChange={checked => handleItemCheck(item.id, checked)}
                  />
                </div>
                
                {/* 商品图片 */}
                <div className="item-image">
                  <img src={url+item.image} alt={item.name} />
                </div>
                
                {/* 商品信息 */}
                <div className="item-info">
                  <div className="item-name">{item.name}</div>
                  <div className="item-price">¥{item.price.toFixed(2)}</div>
                  
                 
                </div>
                 {/* 数量控制 */}
                  <div className="item-quantity">
                    <button 
                      className="quantity-btn"
                      onClick={() => decreaseQuantity(item.id)}
                    >
                      -
                    </button>
                    <span className="quantity">{item.quantity}</span>
                    <button 
                      className="quantity-btn"
                      onClick={() => increaseQuantity(item.id)}
                    >
                      +
                    </button>
                  </div>
              </div>
            ))}
          </div>

            {/* 猜你喜欢 */}
            <div className='cartRank-box'>
            <div className='cartRank-title'>
            <img src={loveLeft} alt="" />
            <span>猜你喜欢</span>
            <img src={loveRight} alt="" />
            </div>
            
             {/* 瀑布流商品列表 */}
                    <div className="waterfall-container">
                      <div className="waterfall-column">
                        {leftColumn.map((item, index) => (
                          <div 
                            className="waterfall-item" 
                            key={`left-${index}`}
                            onClick={() => navigate(`/goods/${item.id}`)}
                          >
                            <img src={url + item.image} alt={item.title} />
                            <p className="waterfall-item-title">{item.title}</p>
                            <p className="waterfall-item-price">¥{item.price}</p>
                            <img 
                            // Deleted: src={cartItems[item.id] ? ok : add} 
                            src={cartItems.some(cartItem => cartItem.commodity_id === item.id) ? ok : add}
                            alt={cartItems.some(cartItem => cartItem.commodity_id === item.id) ? "已添加" : "添加到购物车"}
                            className="add-to-cart-icon"
                            style={{ width: '20px', height: '20px',position: 'absolute', right: '10px', bottom: '9px' }}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleAddToCart(item.id);
                            }}
                          />
                          </div>
                          
                        ))}
                      </div>
                      <div className="waterfall-column">
                        {rightColumn.map((item, index) => (
                          <div 
                            className="waterfall-item" 
                            key={`right-${index}`}
                            onClick={() => navigate(`/goods/${item.id}`)}
                          >
                            <img src={url + item.image} alt={item.title} />
                            <p className="waterfall-item-title">{item.title}</p>
                            <p className="waterfall-item-price">¥{item.price}</p>
                           <img 
                            // Deleted: src={cartItems[item.id] ? ok : add} 
                            src={cartItems.some(cartItem => cartItem.commodity_id === item.id) ? ok : add}
                            alt={cartItems.some(cartItem => cartItem.commodity_id === item.id) ? "已添加" : "添加到购物车"}
                            className="add-to-cart-icon"
                            style={{ width: '20px', height: '20px',position: 'absolute', right: '10px', bottom: '9px' }}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleAddToCart(item.id);
                            }}
                          />
                          </div>
                        ))}
                      </div>
                    </div>
            </div>


          {/* 结算栏 */}
          <div className="cart-footer">
            <div className="footer-left">
              <Checkbox 
                checked={isAllChecked} 
                onChange={handleCheckAll}
              >
                全选
              </Checkbox>
              <div className="total-info">
                <div>合计: ¥{totalPrice.toFixed(2)}</div>
              </div>
            </div>
            <div className="checkout-btn">
              结算({selectedCount})
            </div>
          </div>
        </>
      ) : (
        // 空购物车提示
        <div className="empty-cart">
          <div className="empty-text">购物车为空</div>
          <div className="empty-subtext">去添加一些商品吧</div>
        </div>
      )}


      {/* 底部导航栏 */}
      <div style={{ position: 'fixed', bottom: 0, width: '100%',backgroundColor:'#ffffff' }}>
        <TabBar activeKey={activeKey} onChange={setRouteActive}>
          {tabs.map(item => (
            <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
          ))}
        </TabBar>
      </div>

    </div>
  );
};

export default ShoppingCart;